<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>下拉列表的使用</title>
</head>
<body>
<div id="change" class="change">
    <div>请选择你的最爱</div>
    <label>
        <select name="fruits" multiple>
            <option value="apple">苹果</option>
            <option value="peach">桃子</option>
            <option value="banana">香蕉</option>
            <option value="orange">橘子</option>
            <option value="mongo">芒果</option>
            <option value="watermelon">西瓜</option>
        </select>
    </label>

    <h2>你最爱的水果是：<span>{{ fruit }}</span></h2>
</div>

<script !src="">
    let fruit = []
    let element_select = document.querySelector("select");
    let element_span = document.querySelector("span");

    element_span.innerText = fruit

    // 设置默认不选中任何一项
    element_select.selectedIndex = -1

    element_select.addEventListener(
        "change",
        function () {
            fruit = []
           let selectedOptions = element_select.selectedOptions;
            for (let i = 0; i < selectedOptions.length; i++) {
                fruit.push(selectedOptions[i].value)
                console.log(fruit);
                element_span.innerText = fruit
            }
        }
    )

</script>
</body>
</html>